<template>
	<view class="orders-page">
		<!-- 顶部紫色渐变背景 -->
		<view class="top-bg">
			<view class="bg-shape bg-shape-1"></view>
			<view class="bg-shape bg-shape-2"></view>
			<view class="bg-shape bg-shape-3"></view>
		</view>

		<!-- 返回按钮 -->
		<view class="back-btn" @click="goBack">
			<image class="back-icon" src="/static/icons/back.png" mode="aspectFit"></image>
		</view>

		<scroll-view class="content" scroll-y refresher-enabled @refresherrefresh="onRefresh">
			<!-- 页面标题 -->
			<view class="page-header">
				<view class="header-content">
					<text class="page-title">我的订单</text>
					<text class="page-subtitle">共 {{ totalOrders }} 个订单</text>
				</view>
			</view>

			<!-- 搜索框 -->
			<view class="search-section">
				<view class="search-box">
					<text class="search-icon">🔍</text>
					<input class="search-input" v-model="searchKeyword" placeholder="搜索订单ID或商品名称..."
						@confirm="handleSearch" @input="onSearchInput" />
					<view v-if="searchKeyword" class="search-clear" @click="clearSearch">
						<text>×</text>
					</view>
				</view>
			</view>

			<!-- 订单列表 -->
			<view class="orders-section">
				<view v-if="loading && orders.length === 0" class="loading-state">
					<view class="loading-spinner"></view>
					<text class="loading-text">{{ searchKeyword ? '搜索中...' : '加载订单中...' }}</text>
				</view>

				<view v-else-if="orders.length === 0" class="empty-state">
					<view class="empty-icon">📦</view>
					<text class="empty-title">
						{{ searchKeyword ? '未找到相关订单' : '暂无订单' }}
					</text>
					<text class="empty-desc">
						{{ searchError || (searchKeyword ? '请尝试搜索其他订单ID或商品名称' : '您还没有任何订单记录') }}
					</text>
					<view v-if="searchKeyword" class="empty-action">
						<button class="action-btn" @click="clearSearch">查看全部订单</button>
					</view>
				</view>

				<view v-else class="orders-list">
					<view v-for="order in orders" :key="order.order_id" class="order-card">
						<view class="order-header">
							<view class="order-info">
								<text class="order-id">订单ID：{{ order.order_id }}</text>
								<text class="order-time">{{ order.order_time }}</text>
							</view>
							<view class="order-status">
								<text class="status-badge completed">已完成</text>
							</view>
						</view>

						<view class="order-body">
							<view class="product-info">
								<view class="product-icon">🛒</view>
								<view class="product-details">
									<text class="product-name">{{ order.good_name }}</text>
									<text class="product-spec">商品ID: {{ order.good_id }}</text>
								</view>
							</view>

							<view class="order-details">
								<view class="detail-item">
									<text class="detail-label">购买数量：</text>
									<text class="detail-value">{{ order.order_number }} 件</text>
								</view>
								<view class="detail-item">
									<text class="detail-label">商品单价：</text>
									<text class="detail-value">¥{{ formatPrice(order.good_price) }}</text>
								</view>
								<view class="detail-item">
									<text class="detail-label">订单总价：</text>
									<text class="detail-value total">¥{{ formatPrice(order.total_price) }}</text>
								</view>
							</view>
						</view>

						<!-- 在订单卡片的 order-footer 部分添加地址信息 -->
						<view class="order-footer">
							<view class="user-info">
								<text class="user-name">{{ order.user_name }}</text>
								<text class="user-phone">{{ formatPhone(order.user_phone) }}</text>
								<!-- 添加地址显示 -->
								<text class="user-address"
									v-if="order.address">{{ formatAddress(order.address) }}</text>
								<text class="user-address empty" v-else>未设置地址</text>
							</view>
							<view class="order-actions">
								<button class="action-btn detail" @click="viewOrderDetail(order.order_id)">详情</button>
								<button class="action-btn delete"
									@click="confirmDeleteOrder(order.order_id)">删除</button>
							</view>
						</view>

					</view>
				</view>

				<!-- 加载更多 -->
				<view v-if="hasMore && orders.length > 0 && !searchKeyword" class="load-more">
					<button class="load-more-btn" @click="loadMore" :disabled="loadingMore">
						{{ loadingMore ? '加载中...' : `加载更多 (${orders.length}/${totalOrders})` }}
					</button>
				</view>

				<!-- 没有更多数据 -->
				<view v-if="!hasMore && orders.length > 0 && !searchKeyword" class="no-more">
					<text>已加载全部 {{ totalOrders }} 个订单</text>
				</view>

				<!-- 搜索模式下提示 -->
				<view v-if="searchKeyword && orders.length > 0" class="search-tips">
					<text>搜索到 {{ orders.length }} 个订单</text>
					<text class="tips-action" @click="clearSearch">查看全部</text>
				</view>
			</view>

			<!-- 底部安全区域 -->
			<view class="bottom-space"></view>
		</scroll-view>

		<!-- 创建订单按钮 -->
		<view class="floating-action">
			<button class="fab-btn" @click="showCreateOrder = true">
				<text class="fab-icon">+</text>
			</button>
		</view>

		<!-- 创建订单模态框 -->
		<view class="modal-mask" v-if="showCreateOrder" @click="showCreateOrder = false">
			<view class="modal-content create-order-modal" @click.stop>
				<view class="modal-header">
					<text class="modal-title">创建新订单</text>
					<text class="modal-close" @click="showCreateOrder = false">×</text>
				</view>
				<view class="modal-body">
					<view class="form-item">
						<text class="form-label">商品ID</text>
						<input class="form-input" v-model="newOrder.good_id" placeholder="请输入商品ID" type="number" />
					</view>
					<view class="form-item">
						<text class="form-label">购买数量</text>
						<input class="form-input" v-model="newOrder.order_number" placeholder="请输入购买数量" type="number" />
					</view>

					<!-- 新增地址输入部分 -->
					<view class="form-item">
						<view class="address-header">
							<text class="form-label">收货地址</text>
							<text class="address-tips" @click="toggleAddressInput">
								{{ showAddressInput ? '使用默认地址' : '自定义地址' }}
							</text>
						</view>

						<!-- 默认地址显示 -->
						<view v-if="!showAddressInput && userDefaultAddress" class="default-address">
							<text class="address-text">{{ userDefaultAddress }}</text>
							<text class="address-tag">默认地址</text>
						</view>

						<!-- 自定义地址输入 -->
						<input v-if="showAddressInput" class="form-input" v-model="newOrder.address"
							placeholder="请输入收货地址（格式：姓名，手机号，详细地址）" />

						<view v-if="!userDefaultAddress && !showAddressInput" class="no-address-tip">
							<text class="tip-text">暂无默认地址，请</text>
							<text class="tip-link" @click="showAddressInput = true">输入地址</text>
						</view>
					</view>

					<view v-if="productInfo" class="product-preview">
						<text class="preview-title">商品信息</text>
						<view class="preview-content">
							<text class="product-name">{{ productInfo.good_name }}</text>
							<text class="product-stock">库存: {{ productInfo.good_number }}</text>
							<text class="product-price">售价: ¥{{ formatPrice(productInfo.good_sell_price) }}</text>
						</view>
					</view>
				</view>
				<view class="modal-footer">
					<button class="modal-button cancel" @click="showCreateOrder = false">取消</button>
					<button class="modal-button confirm" @click="createOrder" :disabled="creatingOrder">
						{{ creatingOrder ? '创建中...' : '确认创建' }}
					</button>
				</view>
			</view>
		</view>

		<!-- 订单详情模态框 -->
		<view class="modal-mask" v-if="selectedOrder" @click="selectedOrder = null">
			<view class="modal-content order-detail-modal" @click.stop>
				<view class="modal-header">
					<text class="modal-title">订单详情</text>
					<text class="modal-close" @click="selectedOrder = null">×</text>
				</view>
				<view class="modal-body">
					<view class="detail-section">
						<text class="section-title">基本信息</text>
						<view class="detail-grid">
							<view class="detail-item">
								<text class="detail-label">订单ID：</text>
								<text class="detail-value">{{ selectedOrder.order_id }}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">下单时间：</text>
								<text class="detail-value">{{ selectedOrder.order_time }}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">用户名：</text>
								<text class="detail-value">{{ selectedOrder.user_name }}</text>
							</view>
							<view class="detail-item">
								<text class="detail-label">手机号：</text>
								<text class="detail-value">{{ formatPhone(selectedOrder.user_phone) }}</text>
							</view>
							<!-- 新增地址字段显示 -->
							<view class="detail-item address-item" v-if="selectedOrder.address">
								<text class="detail-label">收货地址：</text>
								<text class="detail-value address-value">{{ selectedOrder.address }}</text>
							</view>
							<view class="detail-item address-item" v-else>
								<text class="detail-label">收货地址：</text>
								<text class="detail-value address-empty">未设置收货地址</text>
							</view>
						</view>
					</view>

					<view class="detail-section">
						<text class="section-title">商品信息</text>
						<view class="product-card">
							<view class="product-icon">🛒</view>
							<view class="product-info">
								<text class="product-name">{{ selectedOrder.good_name }}</text>
								<text class="product-id">商品ID: {{ selectedOrder.good_id }}</text>
							</view>
						</view>
					</view>

					<view class="detail-section">
						<text class="section-title">订单详情</text>
						<view class="order-stats">
							<view class="stat-item">
								<text class="stat-label">购买数量</text>
								<text class="stat-value">{{ selectedOrder.order_number }} 件</text>
							</view>
							<view class="stat-item">
								<text class="stat-label">商品单价</text>
								<text class="stat-value">¥{{ formatPrice(selectedOrder.good_price) }}</text>
							</view>
							<view class="stat-item">
								<text class="stat-label">订单总价</text>
								<text class="stat-value total">¥{{ formatPrice(selectedOrder.total_price) }}</text>
							</view>
						</view>
					</view>
				</view>
				<view class="modal-footer modal-footer-fixed">
					<button class="modal-button delete"
						@click="confirmDeleteOrder(selectedOrder.order_id)">删除订单</button>
					<button class="modal-button confirm" @click="selectedOrder = null">关闭</button>
				</view>
			</view>
		</view>

		<!-- 加载遮罩 -->
		<view class="loading-mask" v-if="globalLoading">
			<view class="loading-spinner"></view>
			<text class="loading-text">处理中...</text>
		</view>
	</view>
</template>

<script>
	const API_BASE_URL = 'http://localhost:8000/api/v1';

	export default {
		name: 'OrdersManagement',
		data() {
			return {
				loading: false,
				loadingMore: false,
				globalLoading: false,
				creatingOrder: false,
				orders: [],
				totalOrders: 0,
				currentPage: 1,
				currentOffset: 0,
				pageSize: 5,
				hasMore: false,
				showCreateOrder: false,
				selectedOrder: null,
				searchKeyword: '',
				searchTimer: null,
				searchError: '',
				newOrder: {
					good_id: '',
					order_number: '',
					address: '' // 新增地址字段
				},
				showAddressInput: false, // 控制地址输入显示
				userDefaultAddress: '', // 用户默认地址
				productInfo: null
			};
		},
		computed: {
			token() {
				return uni.getStorageSync('token');
			}
		},
		onLoad() {
			this.loadOrders();
			this.getUserDefaultAddress(); // 获取用户默认地址
		},
		onShow() {
			this.refreshOrders();
		},
		methods: {
			// 返回首页
			goBack() {
				uni.switchTab({
					url: '/pages/home/home'
				});
			},

			// 加载订单列表
			async loadOrders(isLoadMore = false) {
				if (this.loading && !isLoadMore) return;
				if (this.loadingMore && isLoadMore) return;

				if (isLoadMore) {
					this.loadingMore = true;
				} else {
					this.loading = true;
				}

				try {
					const params = new URLSearchParams({
						limit: this.pageSize,
						offset: isLoadMore ? this.currentOffset : 0
					});

					const response = await new Promise((resolve, reject) => {
						uni.request({
							url: `${API_BASE_URL}/orders/?${params}`,
							method: 'GET',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							success: resolve,
							fail: reject
						});
					});

					if (response.statusCode === 200) {
						const data = response.data;
						let ordersData = data.orders || [];

						// 确保数据包含 good_price 和 total_price 字段
						ordersData = ordersData.map(order => {
							// 如果后端没有返回 total_price，则计算它
							if (!order.total_price && order.good_price && order.order_number) {
								order.total_price = (parseFloat(order.good_price) * parseInt(order
									.order_number)).toFixed(2);
							}
							return order;
						});

						if (isLoadMore) {
							this.orders = [...this.orders, ...ordersData];
						} else {
							this.orders = ordersData;
						}

						this.totalOrders = data.total || 0;

						// 修正 hasMore 的计算逻辑
						if (this.searchKeyword) {
							// 搜索模式下不显示分页
							this.hasMore = false;
							this.currentOffset = 0;
						} else {
							// 正常模式下计算是否有更多数据
							const currentCount = this.orders.length;
							this.hasMore = currentCount < this.totalOrders;

							// 更新 offset
							if (isLoadMore) {
								this.currentOffset += ordersData.length;
							} else {
								this.currentOffset = ordersData.length;
							}

							console.log(
								`分页信息: 已加载 ${currentCount}/${this.totalOrders}, hasMore: ${this.hasMore}, offset: ${this.currentOffset}`
							);
						}

						if (isLoadMore) {
							this.currentPage++;
						} else {
							this.currentPage = 1;
						}
					} else {
						throw new Error(data.detail || '获取订单失败');
					}
				} catch (error) {
					console.error('加载订单失败:', error);
					uni.showToast({
						title: '加载订单失败',
						icon: 'none'
					});
				} finally {
					if (isLoadMore) {
						this.loadingMore = false;
					} else {
						this.loading = false;
					}
				}
			},

			// 刷新订单
			async refreshOrders() {
				this.currentPage = 1;
				this.currentOffset = 0;
				this.searchError = '';
				await this.loadOrders();
			},

			// 加载更多
			async loadMore() {
				if (!this.hasMore || this.searchKeyword) return;
				await this.loadOrders(true);
			},

			// 下拉刷新
			async onRefresh() {
				this.currentPage = 1;
				this.currentOffset = 0;
				this.searchError = '';
				await this.loadOrders();
				uni.stopPullDownRefresh();
			},

			// 获取用户默认地址
			async getUserDefaultAddress() {
				try {
					const response = await new Promise((resolve, reject) => {
						uni.request({
							url: `${API_BASE_URL}/users/address`,
							method: 'GET',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							success: resolve,
							fail: reject
						});
					});

					if (response.statusCode === 200) {
						const data = response.data;
						if (data.has_address) {
							this.userDefaultAddress = data.formatted_address;
							this.newOrder.address = data.formatted_address; // 设置为默认值
						}
					}
				} catch (error) {
					console.error('获取用户地址失败:', error);
				}
			},

			// 切换地址输入模式
			toggleAddressInput() {
				this.showAddressInput = !this.showAddressInput;
				if (!this.showAddressInput) {
					// 切换回默认地址时，恢复默认地址
					this.newOrder.address = this.userDefaultAddress;
				} else {
					// 切换到自定义地址时，清空输入框
					this.newOrder.address = '';
				}
			},

			// 搜索输入处理
			onSearchInput() {
				// 防抖搜索
				clearTimeout(this.searchTimer);
				this.searchTimer = setTimeout(() => {
					this.handleSearch();
				}, 500);
			},

			// 处理搜索
			async handleSearch() {
				if (!this.searchKeyword.trim()) {
					this.searchError = '';
					await this.refreshOrders();
					return;
				}

				this.currentPage = 1;
				this.currentOffset = 0;
				this.searchError = '';

				// 判断搜索类型：数字可能是订单ID或商品ID，文字是商品名称
				const searchValue = this.searchKeyword.trim();
				if (!isNaN(searchValue) && searchValue !== '') {
					// 数字搜索：先尝试订单ID搜索，如果没结果再尝试商品ID搜索
					await this.searchByOrderIdOrGoodId(parseInt(searchValue));
				} else {
					// 文字搜索：商品名称搜索
					await this.searchByKeyword(searchValue);
				}
			},

			// 按订单ID或商品ID搜索
			async searchByOrderIdOrGoodId(id) {
				this.loading = true;
				try {
					// 先尝试订单ID搜索
					let response = await new Promise((resolve, reject) => {
						uni.request({
							url: `${API_BASE_URL}/orders/?order_id=${id}`,
							method: 'GET',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							success: resolve,
							fail: reject
						});
					});

					if (response.statusCode === 200) {
						const data = response.data;
						let ordersData = data.orders || [];

						// 如果找到订单ID的结果，直接显示
						if (ordersData.length > 0) {
							ordersData = this.processOrderData(ordersData);
							this.orders = ordersData;
							this.totalOrders = data.total || 0;
							this.hasMore = false;
							this.searchError = '';
							return;
						}
					}

					// 如果订单ID搜索没结果，尝试商品ID搜索
					response = await new Promise((resolve, reject) => {
						uni.request({
							url: `${API_BASE_URL}/orders/?good_id=${id}`,
							method: 'GET',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							success: resolve,
							fail: reject
						});
					});

					if (response.statusCode === 200) {
						const data = response.data;
						let ordersData = data.orders || [];

						ordersData = this.processOrderData(ordersData);
						this.orders = ordersData;
						this.totalOrders = data.total || 0;
						this.hasMore = false;

						if (ordersData.length === 0) {
							this.searchError = `未查找到订单ID或商品ID为"${this.searchKeyword}"的相关订单`;
						} else {
							this.searchError = '';
						}
					} else {
						throw new Error(data.detail || '搜索失败');
					}
				} catch (error) {
					console.error('搜索失败:', error);
					this.searchError = '搜索失败，请稍后重试';
					this.orders = [];
				} finally {
					this.loading = false;
				}
			},

			// 按关键词搜索（商品名称）
			async searchByKeyword(keyword) {
				this.loading = true;
				try {
					const response = await new Promise((resolve, reject) => {
						uni.request({
							url: `${API_BASE_URL}/orders/?keyword=${encodeURIComponent(keyword)}`,
							method: 'GET',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							success: resolve,
							fail: reject
						});
					});

					if (response.statusCode === 200) {
						const data = response.data;
						let ordersData = data.orders || [];

						ordersData = this.processOrderData(ordersData);
						this.orders = ordersData;
						this.totalOrders = data.total || 0;
						this.hasMore = false;

						if (ordersData.length === 0) {
							this.searchError = `未搜索到相关商品，请您确认商品名称"${this.searchKeyword}"是否正确`;
						} else {
							this.searchError = '';
						}
					} else {
						throw new Error(data.detail || '搜索商品失败');
					}
				} catch (error) {
					console.error('关键词搜索失败:', error);
					this.searchError = '搜索失败，请稍后重试';
					this.orders = [];
				} finally {
					this.loading = false;
				}
			},

			// 处理订单数据（价格字段等）
			processOrderData(ordersData) {
				return ordersData.map(order => {
					if (!order.total_price && order.good_price && order.order_number) {
						order.total_price = (parseFloat(order.good_price) * parseInt(order.order_number)).toFixed(
							2);
					}
					return order;
				});
			},

			// 清除搜索
			async clearSearch() {
				this.searchKeyword = '';
				this.searchError = '';
				await this.refreshOrders();
			},

			// 查看订单详情
			async viewOrderDetail(orderId) {
				this.globalLoading = true;
				try {
					const response = await new Promise((resolve, reject) => {
						uni.request({
							url: `${API_BASE_URL}/orders/${orderId}`,
							method: 'GET',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							success: resolve,
							fail: reject
						});
					});

					if (response.statusCode === 200) {
						let orderData = response.data;
						console.log('订单详情数据:', orderData); // 调试日志，查看地址字段

						// 确保详情数据也包含正确的价格字段
						if (!orderData.total_price && orderData.good_price && orderData.order_number) {
							orderData.total_price = (parseFloat(orderData.good_price) * parseInt(orderData
								.order_number)).toFixed(2);
						}

						// 处理地址字段，确保正确显示
						if (orderData.address && typeof orderData.address === 'string') {
							// 地址已经是字符串，直接使用
							console.log('地址内容:', orderData.address);
						} else if (orderData.address === null || orderData.address === undefined) {
							// 地址为空
							orderData.address = '';
						}

						this.selectedOrder = orderData;
					} else {
						throw new Error(response.data.detail || '获取订单详情失败');
					}
				} catch (error) {
					console.error('获取订单详情失败:', error);
					uni.showToast({
						title: '获取订单详情失败',
						icon: 'none'
					});
				} finally {
					this.globalLoading = false;
				}
			},

			// 创建订单
			async createOrder() {
				if (!this.newOrder.good_id || !this.newOrder.order_number) {
					uni.showToast({
						title: '请填写完整的订单信息',
						icon: 'none'
					});
					return;
				}

				// 检查地址
				if (!this.newOrder.address) {
					uni.showToast({
						title: '请填写收货地址',
						icon: 'none'
					});
					return;
				}

				this.creatingOrder = true;
				try {
					const orderData = {
						good_id: parseInt(this.newOrder.good_id),
						order_number: parseInt(this.newOrder.order_number),
						address: this.newOrder.address // 添加地址参数
					};

					console.log('创建订单数据:', orderData); // 调试日志

					const response = await new Promise((resolve, reject) => {
						uni.request({
							url: `${API_BASE_URL}/orders/`,
							method: 'POST',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							data: orderData,
							success: resolve,
							fail: reject
						});
					});

					if (response.statusCode === 200) {
						uni.showToast({
							title: '订单创建成功',
							icon: 'success'
						});
						this.showCreateOrder = false;
						this.resetOrderForm();
						await this.refreshOrders();
					} else {
						throw new Error(response.data.detail || '创建订单失败');
					}
				} catch (error) {
					console.error('创建订单失败:', error);
					uni.showToast({
						title: error.message || '创建订单失败',
						icon: 'none'
					});
				} finally {
					this.creatingOrder = false;
				}
			},

			// 重置订单表单
			resetOrderForm() {
				this.newOrder = {
					good_id: '',
					order_number: '',
					address: this.userDefaultAddress // 重置时保留默认地址
				};
				this.showAddressInput = false;
				this.productInfo = null;
			},

			// 确认删除订单
			confirmDeleteOrder(orderId) {
				// 先关闭其他可能打开的模态框
				this.selectedOrder = null;
				this.showCreateOrder = false;

				// 添加短暂延迟确保其他模态框完全关闭
				setTimeout(() => {
					uni.showModal({
						title: '确认删除',
						content: '确定要删除这个订单吗？此操作不可恢复。',
						confirmColor: '#FF4444',
						confirmText: '删除',
						cancelText: '取消',
						success: async (res) => {
							if (res.confirm) {
								await this.deleteOrder(orderId);
							}
						}
					});
				}, 50);
			},

			// 删除订单
			async deleteOrder(orderId) {
				this.globalLoading = true;
				try {
					const response = await new Promise((resolve, reject) => {
						uni.request({
							url: `${API_BASE_URL}/orders/${orderId}`,
							method: 'DELETE',
							header: {
								'Authorization': `Bearer ${this.token}`,
								'Content-Type': 'application/json'
							},
							success: resolve,
							fail: reject
						});
					});

					if (response.statusCode === 200) {
						uni.showToast({
							title: '订单删除成功',
							icon: 'success'
						});
						this.selectedOrder = null;
						await this.refreshOrders();
					} else {
						throw new Error(response.data.detail || '删除订单失败');
					}
				} catch (error) {
					console.error('删除订单失败:', error);
					uni.showToast({
						title: error.message || '删除订单失败',
						icon: 'none'
					});
				} finally {
					this.globalLoading = false;
				}
			},

			// 格式化地址
			formatAddress(address) {
				if (!address) return '';
				// 如果地址太长，可以适当截断
				if (address.length > 20) {
					return address.substring(0, 20) + '...';
				}
				return address;
			},

			// 格式化价格
			formatPrice(price) {
				if (!price) return '0.00';
				return parseFloat(price).toFixed(2);
			},

			// 格式化手机号
			formatPhone(phone) {
				if (!phone) return '';
				return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
			}
		}
	};
</script>

<style scoped>
	/* 返回按钮样式 */
	.back-btn {
		position: fixed;
		top: 80rpx;
		left: 30rpx;
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.9);
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
		z-index: 1000;
		backdrop-filter: blur(10px);
	}

	.back-icon {
		width: 32rpx;
		height: 32rpx;
	}

	/* 搜索框样式 */
	.search-section {
		margin-bottom: 30rpx;
	}

	.search-box {
		position: relative;
		background: rgba(255, 255, 255, 0.9);
		border-radius: 20rpx;
		padding: 20rpx 24rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 4rpx 16rpx rgba(138, 43, 226, 0.1);
		border: 1rpx solid rgba(255, 255, 255, 0.6);
	}

	.search-icon {
		font-size: 28rpx;
		color: #999;
		margin-right: 16rpx;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.search-input::placeholder {
		color: #999;
	}

	.search-clear {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background: #f0f0f0;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #999;
	}

	/* 搜索提示 */
	.search-tips {
		text-align: center;
		padding: 30rpx;
		background: #f8f9fa;
		border-radius: 16rpx;
		margin-top: 20rpx;
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.search-tips text:first-child {
		font-size: 26rpx;
		color: #666;
	}

	.tips-action {
		font-size: 26rpx;
		color: #8A2BE2;
		text-decoration: underline;
	}

	/* 地址相关样式 */
	.address-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.address-tips {
		font-size: 24rpx;
		color: #8A2BE2;
		text-decoration: underline;
	}

	.default-address {
		background: #f0f8ff;
		border: 1rpx solid #e0e0e0;
		border-radius: 12rpx;
		padding: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.address-text {
		font-size: 26rpx;
		color: #333;
		flex: 1;
		margin-right: 16rpx;
	}

	.address-tag {
		font-size: 22rpx;
		color: #8A2BE2;
		background: #f0ebff;
		padding: 4rpx 12rpx;
		border-radius: 6rpx;
	}

	.no-address-tip {
		text-align: center;
		padding: 30rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
	}

	.tip-text {
		font-size: 26rpx;
		color: #666;
	}

	.tip-link {
		font-size: 26rpx;
		color: #8A2BE2;
		text-decoration: underline;
		margin-left: 8rpx;
	}

	/* 空状态操作按钮 */
	.empty-action {
		margin-top: 30rpx;
	}

	.action-btn {
		padding: 20rpx 40rpx;
		background: linear-gradient(135deg, #8A2BE2, #9370DB);
		color: white;
		border: none;
		border-radius: 12rpx;
		font-size: 26rpx;
	}

	/* 订单详情样式调整 */
	.order-details {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.detail-value.total {
		color: #8A2BE2;
		font-weight: 600;
		font-size: 28rpx;
	}

	.stat-value.total {
		color: #8A2BE2;
		font-size: 30rpx;
	}

	/* 修复详情模态框底部按钮布局 */
	.modal-footer-fixed {
		position: sticky;
		bottom: 0;
		background: white;
		padding-top: 20rpx;
		border-top: 1rpx solid #f0f0f0;
	}

	/* 其他原有样式保持不变 */
	.orders-page {
		position: relative;
		min-height: 100vh;
		background: linear-gradient(180deg, #f9f7ff 0%, #f0ebff 100%);
	}

	.top-bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 300rpx;
		background: linear-gradient(135deg, #8A2BE2 0%, #9370DB 50%, #DA70D6 100%);
		z-index: 0;
		overflow: hidden;
	}

	.bg-shape {
		position: absolute;
		border-radius: 50%;
		background: rgba(255, 255, 255, 0.1);
	}

	.bg-shape-1 {
		width: 200rpx;
		height: 200rpx;
		top: -100rpx;
		right: -50rpx;
	}

	.bg-shape-2 {
		width: 150rpx;
		height: 150rpx;
		bottom: 30rpx;
		left: -60rpx;
	}

	.bg-shape-3 {
		width: 100rpx;
		height: 100rpx;
		top: 80rpx;
		left: 25%;
	}

	.content {
		position: relative;
		z-index: 1;
		height: 100vh;
		padding: 30rpx 24rpx;
		box-sizing: border-box;
	}

	.page-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		padding-top: 40rpx;
	}

	.header-content {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
	}

	.page-title {
		font-size: 40rpx;
		font-weight: 700;
		color: #333;
		display: block;
		margin-bottom: 8rpx;
	}

	.page-subtitle {
		font-size: 26rpx;
		color: #666;
		display: block;
	}

	/* 订单卡片样式 */
	.orders-section {
		margin-bottom: 40rpx;
	}

	.order-card {
		background: rgba(255, 255, 255, 0.9);
		border-radius: 24rpx;
		padding: 32rpx;
		margin-bottom: 24rpx;
		backdrop-filter: blur(10px);
		box-shadow: 0 6rpx 24rpx rgba(138, 43, 226, 0.1);
		border: 1rpx solid rgba(255, 255, 255, 0.6);
	}

	.order-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
		padding-bottom: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.order-info {
		flex: 1;
	}

	.order-id {
		font-size: 30rpx;
		font-weight: 600;
		color: #333;
		display: block;
		margin-bottom: 8rpx;
	}

	.order-time {
		font-size: 24rpx;
		color: #888;
	}

	.order-status {
		flex-shrink: 0;
	}

	.status-badge {
		padding: 8rpx 20rpx;
		border-radius: 20rpx;
		font-size: 22rpx;
		font-weight: 500;
	}

	.status-badge.completed {
		background: #e8f5e8;
		color: #2e7d32;
	}

	.order-body {
		margin-bottom: 24rpx;
	}

	.product-info {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.product-icon {
		width: 60rpx;
		height: 60rpx;
		border-radius: 16rpx;
		background: linear-gradient(135deg, #e6ccff, #d9b3ff);
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
		font-size: 28rpx;
	}

	.product-details {
		flex: 1;
	}

	.product-name {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
		display: block;
		margin-bottom: 6rpx;
	}

	.product-spec {
		font-size: 24rpx;
		color: #888;
	}

	.order-footer {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 20rpx;
		border-top: 1rpx solid #f0f0f0;
	}

	.user-info {
		flex: 1;
	}

	.user-name {
		font-size: 26rpx;
		color: #333;
		display: block;
		margin-bottom: 4rpx;
	}

	.user-phone {
		font-size: 24rpx;
		color: #888;
	}

	.order-actions {
		display: flex;
		gap: 16rpx;
	}

	.action-btn.detail {
		padding: 12rpx 24rpx;
		background: #f0f0f0;
		color: #333;
		border: none;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	.action-btn.delete {
		padding: 12rpx 24rpx;
		background: #ffebee;
		color: #d32f2f;
		border: none;
		border-radius: 8rpx;
		font-size: 24rpx;
		font-weight: 500;
	}

	/* 加载状态 */
	.loading-state,
	.empty-state {
		text-align: center;
		padding: 120rpx 0;
	}

	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid #f3f3f3;
		border-top: 4rpx solid #8A2BE2;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin: 0 auto 20rpx;
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}

	.loading-text {
		font-size: 28rpx;
		color: #666;
	}

	.empty-icon {
		font-size: 80rpx;
		margin-bottom: 20rpx;
		display: block;
	}

	.empty-title {
		font-size: 32rpx;
		color: #333;
		display: block;
		margin-bottom: 12rpx;
		font-weight: 600;
	}

	.empty-desc {
		font-size: 26rpx;
		color: #888;
		line-height: 1.5;
	}

	/* 地址相关样式 */
	.address-item {
		grid-column: 1 / -1;
		/* 让地址项占据整行 */
		margin-top: 8rpx;
	}

	.address-value {
		color: #333;
		font-size: 26rpx;
		line-height: 1.4;
		word-break: break-all;
	}

	.address-empty {
		color: #999;
		font-style: italic;
	}

	/* 订单卡片中的地址样式 */
	.user-address {
		font-size: 22rpx;
		color: #666;
		display: block;
		margin-top: 4rpx;
		line-height: 1.3;
		max-width: 300rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.user-address.empty {
		color: #999;
		font-style: italic;
	}

	/* 调整订单卡片布局以适应新增的地址字段 */
	.order-footer .user-info {
		flex: 1;
		min-width: 0;
		/* 允许内容收缩 */
	}

	/* 确保详情模态框中的地址显示美观 */
	.detail-grid {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 16rpx;
	}

	/* 响应式调整 */
	@media (max-width: 375px) {
		.detail-grid {
			grid-template-columns: 1fr;
		}
	}

	/* 加载更多 */
	.load-more,
	.no-more {
		text-align: center;
		padding: 40rpx 0;
	}

	.load-more-btn {
		background: linear-gradient(135deg, #8A2BE2, #9370DB);
		color: white;
		border: none;
		border-radius: 25rpx;
		padding: 20rpx 60rpx;
		font-size: 28rpx;
		font-weight: 500;
	}

	.load-more-btn:disabled {
		background: #ccc;
	}

	.no-more {
		color: #999;
		font-size: 26rpx;
	}

	/* 悬浮按钮 */
	.floating-action {
		position: fixed;
		bottom: 120rpx;
		right: 40rpx;
		z-index: 1000;
	}

	.fab-btn {
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		background: linear-gradient(135deg, #8A2BE2, #9370DB);
		color: white;
		border: none;
		box-shadow: 0 8rpx 32rpx rgba(138, 43, 226, 0.3);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.fab-icon {
		font-size: 48rpx;
		font-weight: 300;
	}

	/* 模态框样式 */
	.modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 2000;
		padding: 40rpx;
	}

	.modal-content {
		background: white;
		border-radius: 24rpx;
		width: 100%;
		max-width: 600rpx;
		max-height: 80vh;
		overflow: hidden;
		box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.2);
	}

	.create-order-modal {
		max-width: 500rpx;
	}

	.order-detail-modal {
		max-width: 560rpx;
		max-height: 70vh;
		display: flex;
		flex-direction: column;
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 40rpx 32rpx 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
		flex-shrink: 0;
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.modal-close {
		font-size: 40rpx;
		color: #999;
		padding: 10rpx;
	}

	.modal-body {
		padding: 32rpx;
		flex: 1;
		overflow-y: auto;
	}

	.form-item {
		margin-bottom: 32rpx;
	}

	.form-label {
		display: block;
		font-size: 28rpx;
		color: #333;
		margin-bottom: 16rpx;
		font-weight: 500;
	}

	.form-input {
		width: 100%;
		padding: 24rpx;
		border: 1rpx solid #e0e0e0;
		border-radius: 12rpx;
		font-size: 28rpx;
		background: #f9f9f9;
	}

	.product-preview {
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 24rpx;
		margin-top: 20rpx;
	}

	.preview-title {
		font-size: 26rpx;
		color: #333;
		font-weight: 500;
		display: block;
		margin-bottom: 16rpx;
	}

	.preview-content {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.product-name {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
	}

	.product-stock,
	.product-price {
		font-size: 24rpx;
		color: #666;
	}

	.modal-footer {
		display: flex;
		padding: 0 32rpx 32rpx;
		gap: 20rpx;
		flex-shrink: 0;
	}

	.modal-button {
		flex: 1;
		padding: 24rpx;
		border: none;
		border-radius: 12rpx;
		font-size: 28rpx;
		font-weight: 500;
	}

	.modal-button.cancel {
		background: #f5f5f5;
		color: #666;
	}

	.modal-button.confirm {
		background: linear-gradient(135deg, #8A2BE2, #9370DB);
		color: white;
	}

	.modal-button.delete {
		background: #ffebee;
		color: #d32f2f;
	}

	.modal-button:disabled {
		background: #ccc;
		color: #999;
	}

	/* 详情页面样式 */
	.detail-section {
		margin-bottom: 32rpx;
	}

	.section-title {
		font-size: 28rpx;
		font-weight: 600;
		color: #333;
		display: block;
		margin-bottom: 20rpx;
	}

	.detail-grid {
		display: grid;
		gap: 16rpx;
	}

	.product-card {
		display: flex;
		align-items: center;
		background: #f8f9fa;
		border-radius: 12rpx;
		padding: 24rpx;
	}

	.order-stats {
		display: grid;
		grid-template-columns: 1fr;
		gap: 16rpx;
	}

	.stat-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
	}

	.stat-label {
		font-size: 26rpx;
		color: #666;
	}

	.stat-value {
		font-size: 28rpx;
		color: #333;
		font-weight: 600;
	}

	/* 全局加载遮罩 */
	.loading-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(255, 255, 255, 0.9);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		z-index: 3000;
	}

	.bottom-space {
		height: 40rpx;
	}
</style>